package com.ray.export.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author bo shen
 * @Description: 读取头
 * @Class: HeadReadListener
 * @Package com.ray.file.excel
 * @date 2019/11/25 11:07
 * @company <p>杭州传化陆鲸科技有限公司</p>
 * @updateRecord time(修改时间)  author(修改人)   desc(修改内容)
 */
@Slf4j
public class HeadReadListener<T> extends AnalysisEventListener<T> {

    Map<String, ExcelSheet<T>> contents = new HashMap<>();

    @Override
    public void onException(Exception exception, AnalysisContext context) throws Exception {
        log.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(),
                    excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
        }
    }

    @Override
    public void invoke(T data, AnalysisContext context) {

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    /**
     * 这里会一行行的返回头
     *
     * @param headMap
     * @param context
     */
    @Override
    public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
        ExcelSheet<T> excelSheet = contents.get(context.getCurrentSheet().getSheetName());
        if (ObjectUtils.isEmpty(excelSheet)) {
            excelSheet = new ExcelSheet<>();
            excelSheet.setSheetName(context.getCurrentSheet().getSheetName());
        }
        excelSheet.setHead(headMap);
        contents.put(context.getCurrentSheet().getSheetName(), excelSheet);
    }


    public Map<String, ExcelSheet<T>> getContents() {
        return contents;
    }

}
